<template>


	<div align="right" class="mb-4 flex justify-end w-full">
		<el-button
			type="primary"
			@click="getPage()"
			class="bg-blue-100 text-blue-600 hover:bg-blue-200"
		>
			<i class="el-icon-search mr-2"/>查询
		</el-button>
	</div>


	<!-- 数据表格 -->
	<el-table :data="paginatedData" border>
		<el-table-column prop="fileName" label="文件名称"  />
<!--		<el-table-column prop="fileUrl" label="文件地址" >-->
<!--		</el-table-column>-->
		<el-table-column prop="fileUrl" label="文件地址" width="220" align="center">
			<template #default="{row}">
				<div class="file-link">
					<!-- 图片类型展示预览 -->
					<el-image
						v-if="isImageType(row.fileUrl)"
						style="width: 80px; height: 40px; cursor: pointer"
						:src="row.fileUrl"
						:preview-src-list="[row.fileUrl]"
						fit="contain"
						close-on-click-modal
						preview-teleported
						:z-index="9999"
					>
						<template #error>
							<div class="text-gray-400">预览加载失败</div>
						</template>
					</el-image>

					<!-- 非图片类型展示跳转链接 -->
					<a
						v-else
						:href="row.fileUrl"
						target="_blank"
						class="text-blue-600 hover:text-blue-800 truncate"
					>
						{{ getFileName(row.fileUrl) }}
						<el-tag
							size="mini"
							:type="getFileTagType(row.fileUrl)"
							class="ml-2"
						>
							{{ getFileExtension(row.fileUrl) }}
						</el-tag>
					</a>
				</div>
			</template>
		</el-table-column>
		<el-table-column prop="oaDocumentFollowupUserParamList" label="接收人">
			<template #default="{row}">
				<!-- 直接显示第一个接收人 -->
				<el-tag v-if="row.oaDocumentFollowupUserParamList && row.oaDocumentFollowupUserParamList.length > 0">
					{{ row.oaDocumentFollowupUserParamList[0].recipientName }}
				</el-tag>

				<!-- 或者显示所有接收人 -->
<!--				<div v-if="row.oaDocumentFollowupUserParamList">-->
<!--					<el-tag-->
<!--						v-for="(user, index) in row.oaDocumentFollowupUserParamList"-->
<!--						:key="index"-->
<!--						style="margin-right: 5px; margin-bottom: 5px"-->
<!--					>-->
<!--						{{ user.recipientName }}-->
<!--					</el-tag>-->
<!--				</div>-->
			</template>
		</el-table-column>
		<el-table-column prop="pusherName" label="推送人"/>
		<el-table-column label="消息状态" prop="messageStatus" >
			<template #default="{row}">
			<span
				v-if="!row.messageStatus ||row.messageStatus === '0'"
				:style="{ color: 'red' }">未读</span>
				<span
					v-else-if="row.messageStatus === '1'"
					:style="{ color: 'green' }">已读</span>
				<span
					v-else-if="row.messageStatus === '2'"
					:style="{ color: 'blue' }">收到</span>
			</template>
		</el-table-column>
		<el-table-column prop="pushTime" label="推送时间" />
		<el-table-column label="操作" width="150">
			<template #default="{row}">
				<el-button v-if="row.messageStatus !== '2'" size="small" @click="received(row)">收到</el-button>
			</template>
		</el-table-column>
	</el-table>

	<!-- 分页组件 -->
	<el-pagination
		v-model:current-page="currentPage"
		:page-size="pageSize"
		layout="total, prev, pager, next"
		:total="total"
		class="mt-4"
		@current-change="currentChange"
	/>

	<!-- 表单弹窗 -->
	<el-dialog title="dialogTitle" v-model="dialogVisible" width="600px">
		<el-form :model="formData" label-width="100px" ref="formRef" :rules="rules">
			<el-form-item label="附件上传" prop="file">
				<el-upload
					:action="action"
					:file-list="fileList"
					:before-upload="beforeUpload"
					:on-success="handleSuccess"
				>
					<el-button type="primary">点击上传</el-button>
					<template #tip>
						<div class="el-upload__tip">支持格式：doc/pdf/图片/视频（单文件≤50MB）</div>
					</template>
				</el-upload>
			</el-form-item>

			<el-form-item label="必看人员" prop="recipientsId">
				<el-select v-model="formData.recipientsId" multiple placeholder="请选择人员">
					<el-option
						v-for="user in users"
						:key="user.id"
						:label="user.userName"
						:value="user.id"
					/>
				</el-select>
			</el-form-item>
		</el-form>

		<template #footer>
			<el-button @click="dialogVisible = false">取消</el-button>
			<el-button type="primary" @click="submitForm">提交</el-button>
		</template>
	</el-dialog>
</template>
<script>
import {FINANCE_CODES} from '@/config/statusCodes'

export default {
	data() {
		return {
			paginatedData: [], // 初始化数据需要移到外部
			fileUrl: '',
			fileName: '',
			action: '/capi/get/uploadFileByCode?code=' + FINANCE_CODES.DOCUMENT_FOLLOW_UP,
			total: 0,
			currentPage: 1,
			pageSize: 15,
			dialogVisible: false,
			userInfo: {},
			formData: {
				id: null,
				leader: '',
				file: null,
				recipientsId: []
			},
			fileList: [],
			users: [],
			rules: {
				leader: [{required: true, message: '请选择负责人'}],
				recipientsId: [{type: 'array', required: true, message: '至少选择1位必看人员'}],
				file: [{required: true, message: '请上传文件'}]
			}
		}
	},
	computed: {
	},
	mounted() {
		this.getUsers();
		this.userInfo = this.$TOOL.data.get("USER_INFO");
		console.log('userInfo', this.userInfo)
		this.getPage();
	},
	methods: {
		received(row){
			this.$API.office.documentationFollowThrough.editMessageStatus.postPro({messageStatus:'2',id:row.topicId}).then(res => {
				this.$message.success('修改消息状态成功')
				this.getPage();
			}).catch(err => {
				this.$message.error('修改消息状态失败')
			})
		},
		currentChange(val){
			this.currentPage = val;
			console.log('currentPage', this.currentPage)
			this.getPage()
		},
		getUsers(){
			this.$API.office.documentationFollowThrough.getUserInfoAll.get().then(res => {
				 	this.users = res.data;
				console.log('users',this.users)
			}).catch(err => {
				this.$message.error('获取用户失败')
			})
		},
		getPage() {
			this.$API.office.documentationFollowThrough.getByRecipients.get(
				{
					recipientsId: this.userInfo.id,  // 审批人/查看人
					page: this.currentPage,
					pageSize: this.pageSize
				}
			).then(res => {
				console.log('res.data.list', res.data.list)
				this.paginatedData = res.data.list;
				this.total = parseInt(res.data.total, 10); // 将字符串转换为数字
				this.paginatedData.forEach(item => {
					// if (item.fileUrl) {
						// item.fileName = item.fileUrl.split('/').pop()
					// }
				})
			}).catch(err => {
				this.$message.error('分页失败')
			})
		},
		getRecipientsPage() {
			this.$API.office.documentationFollowThrough.getByRecipients.get(
				{
					recipientsId: this.userInfo.id,
				}
			).then(res => {
				console.log('res.data.list', res.data.list)
				this.paginatedData = res.data.list;
			}).catch(err => {
				this.$message.error('分页失败')
			})
		},
		beforeUpload(file) {
			const isLt50M = file.size / 1024 / 1024 < 50
			if (!isLt50M) {
				this.$message.error('文件大小不能超过50MB!')
				return false
			}
			return true
		},
		handleSuccess(response, file) {
			console.log('response', response)
			console.log('response.url', response.redirect)
			this.fileUrl = response.redirect
			// this.formData.file = {
			// 	name: file.name,
			// 	url: response.redirect
			// }
			this.fileList = [{name: file.name, url: response.redirect}];
		},
		openDialog(row) {
			if (row && typeof row === 'object') {
				Object.assign(this.formData, row);
				if (row.fileUrl) {
					this.fileUrl = row.fileUrl;
					// const fileName = row.fileUrl.split('/').pop();
					this.fileList = [{name: row.fileName, url: row.fileUrl}];
				} else {
					this.fileList = [];
					console.warn('row.fileUrl is missing or invalid:', row);
				}
			} else {
				this.resetForm();
				console.warn('Invalid row object:', row);
			}
			this.dialogVisible = true;
			console.log('row', this.formData);
		},
		submitForm() {
				// Enhanced validation
				if (!this.fileList || this.fileList.length === 0  ) {
					this.$message.error('请上传至少一个文件')
					return
				}

				if (!Array.isArray(this.formData.recipientsId) ||
					this.formData.recipientsId.length === 0 ||
					this.formData.recipientsId.some(id => !id || (typeof id === 'string' && id.trim() === ''))) {
					this.$message.error('请至少选择一位有效的必看人员')
					return
				}

			let params = {
				pusherId: this.userInfo.id,
				recipientsId: this.formData.recipientsId,
				// fileUrl: "http://oa-oss-attachment.oss-cn-beijing.aliyuncs.com/purchase/dianziqianming/9046975504837.png",
				fileUrl: this.fileUrl,
			};
			console.log('formData', params)
			if (this.formData.id) {
				params.id = this.formData.id
				this.$API.office.documentationFollowThrough.update.postPro(params).then(res => {
					this.getPage();
				})
					.catch(err => {
						this.$message.error('编辑失败')
					})
			} else {
				this.$API.office.documentationFollowThrough.add.postPro(params).then(res => {
					this.getPage();
				})
					.catch(err => {
						this.$message.error('添加失败')
					})
			}

			this.dialogVisible = false
			this.$message.success('操作成功')
		},
		handleDelete(id) {
			console.log('id',id)
			this.$confirm('确认删除该记录？', '警告', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				this.$API.office.documentationFollowThrough.deleteById.del({id:id}).then(res => {
					this.getPage();
					this.$message.success('删除成功')
				}).catch(err => {
						this.$message.success('删除失败')
					})
			})
		},
		resetForm() {
			this.formData.id = null
			this.formData.leader = ''
			this.formData.recipientsId = []
			// this.formData.file = null
			this.fileList = []
		},// 获取文件扩展名（带MIME类型校验更准确）
		getFileExtension(url) {
			const ext = url.split('.').pop().toLowerCase()
			const mimeMap = {
				png: 'image/png',
				jpg: 'image/jpeg',
				jpeg: 'image/jpeg',
				gif: 'image/gif',
				pdf: 'application/pdf',
				doc: 'application/msword',
				docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
			}
			return mimeMap[ext] ? ext : 'file'
		},

		// 判断是否为图片类型（根据MIME类型）
		isImageType(url) {
			const imageTypes = ['png','jpg','jpeg','gif','webp','bmp']
			return imageTypes.includes(this.getFileExtension(url))
		},

		// 获取带后缀的文件名
		getFileName(url) {
			return url.split('/').pop().substring(0, 20) + (url.length > 20 ? '...' : '')
		},

		// 获取文件标签样式类型
		getFileTagType(url) {
			const typeMap = {
				pdf: 'danger',
				doc: 'primary',
				docx: 'primary',
				xls: 'warning',
				xlsx: 'warning',
				ppt: 'success',
				pptx: 'success'
			}
			return typeMap[this.getFileExtension(url)] || 'info'
		}
	}
}

</script>
<style scoped>
/* 添加样式 */
.file-link {
	@apply flex items-center;
}

.file-thumbnail {
	@apply w-16 h-16 rounded cursor-pointer shadow hover:shadow-md transition-all;
}

.el-image__error {
	@apply flex items-center justify-center bg-gray-100;
}

.el-tag {
	@apply transform scale-90;
}
</style>
